<?php

/**
 * 活动信息表
 */
use Common\Bridge;
use lib\core\AdminAction;

define('SITE_AUTH', 'act-list');
require('../../../common.inc.php');

class act extends AdminAction
{
    private $pdo_r;
    private $primary_key = 'Id';
    private $list_url = '/data/modules/act/act.php';

    public function doDefault()
    {
        $param['Id'] = (int)$_GET['Id'];
        $param['ShopId'] = (int)($_GET['ShopId']);
        $param['Status'] = (int)($_GET['Status']);
        $param['Name'] = trim($_GET['Name']);

        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "1";
        if ($param['Id'] > 0) {
            $where .= " AND Id = " . $param['Id'];
        }

        if ($param['Name'] != '') {
            $where .= " AND Name LIKE '%" . $param['Name'] . "%'";
        }

        if ($param['ShopId'] > 0) {
            $where .= " AND ShopId = " . $param['ShopId'];
        }
        if ($param['Status'] > 0) {
            $where .= " AND Status = " . $param['Status'];
        }

        $primary_key = $this->primary_key;
        $count_sql = "SELECT COUNT(*) AS `num` FROM `Active` WHERE $where";

        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $sql = "SELECT * FROM `Active` WHERE $where Order by `Status` ASC LIMIT $offset, $limit";
        $data = $this->readDb($sql);

        $smarty = $this->app->page();
        if ($count > 0) {
            if (!empty($data)) {
                $smarty->value('list', $data);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }

        $smarty->value('param', $param);
        $smarty->value('status_arr', [1 => '正在进行', 2 => '已结束']);
        $smarty->output('act/actList.tpl');
    }

    /**
     * 利用SQL语句读取数据库并返回相应数据
     *
     * @param $sql
     * @return mixed
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_W);
        }

        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }

    /**
     *
     */
    public function doEdit()
    {
        $id = (int)$_GET['Id'];
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }

        $sql = "SELECT * FROM Active WHERE Id = $id";
        $list = $this->readDb($sql);

        $smarty = $this->app->page();
        $smarty->value('info', current($list));
        $smarty->output('act/actedit.tpl');
    }

    /**
     *
     */
    public function doList()
    {
        $id = (int)$_GET['Id'];
        $uid = (int)$_POST['UserId'];
        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }
        $count_sql = "SELECT COUNT(*) AS `num` FROM `ActiveOffer` WHERE ActiveId = $id";
        $where = '';
        if ($uid > 0) {
            $count_sql .= ' and UserId = ' . $uid;
            $where = ' and UserId = ' . $uid;
        }
        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $smarty = $this->app->page();
        $sql = "SELECT * FROM ActiveOffer WHERE ActiveId=$id " . $where . " order by Status DESC, OfferPrice DESC limit $offset, $limit";
        $list = $this->readDb($sql);
        if ($count > 0) {
            if (!empty($data)) {
                $smarty->value('list', $data);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }

        $smarty->value('list', $list);
        $smarty->value('id', $id);
        $smarty->value('uid', $uid > 0 ? $uid : '');
        $smarty->output('act/actofferlist.tpl');
    }

    public function doAdd()
    {
        $smarty = $this->app->page();
//        $smarty->value('info', current($list));
        $smarty->output('act/actadd.tpl');
    }

    public function doUpdate()
    {
        $id = intval($_POST['Id']);
        if (empty($id) || empty($_POST['Name'])) {
            HDshowMsg('修改失败1！', ['type' => 'error', 'url' => $this->list_url]);
        }

        //上传图片
        $img = $_FILES['Cover'];
        if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
            // 复制图片
            $imgUrlAddre = self::saveImageUrl($id, $_FILES['Cover']);
        } else {
            $imgUrlAddre = false;
        }

        $img2 = $_FILES['ImgUrl'];
        if (isset($img2['name']) && $img2['error'] == 0 && $img2['size'] > 0) {
            // 复制图片
            $imgUrlAddre2 = self::saveImageUrl($id, $_FILES['ImgUrl'], 2);
        } else {
            $imgUrlAddre2 = false;
        }
        $data = [
            'ShopId' => intval($_POST['ShopId']),
            'CityId' => intval($_POST['CityId']),
            'Name' => trim($_POST['Name']),
            'Description' => trim($_POST['Description']),
            'StartTime' => trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'MinPrice' => $_POST['MinPrice'],
            'MaxPrice' => $_POST['MaxPrice'],
            'PriceType' => intval($_POST['PriceType']),
            'Rules' => trim($_POST['Rules']),
            'Sort' => intval($_POST['Sort']),
            'MaxOffer' => intval($_POST['MaxOffer']),
            'RewardType' => intval($_POST['RewardType']),
            'RewardDays' => intval($_POST['RewardDays']),
            'CouponId' => intval($_POST['CouponId']),
            'Amount' => intval($_POST['Amount']),
            'Status' => intval($_POST['Status']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        if ($imgUrlAddre !== false) {
            $data['Cover'] = $imgUrlAddre;
        }
        if ($imgUrlAddre2 !== false) {
            $data['ImgUrl'] = $imgUrlAddre2;
        }

        $rel = \Center\Active::update($id, $data);
        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    /**
     * @param $filename
     * @return bool|string
     */
    private static function saveImageUrl($id, $filename, $type = 1)
    {
        ///
        if  ($type == 1) {
            $upload_dir = \Common\ResourcePathManager::getActCoverImgSavePath();
        } else {
            $upload_dir = \Common\ResourcePathManager::getActContentImgSavePath();
        }


        $hash = \Common\PhotoImage::getImageHash($id);
        //$src_img = $upload_dir . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
        $image_status = \Common\PhotoImage::checkImage($filename);

        if ($image_status['code'] == 4) {
            $image_status = \Common\PhotoImage::checkImageByUrl($filename);

            if ($image_status['code'] == 4) {
                return false;
            }
        }

        //配置图片上传目录
        $cfg = [
            'base' => $upload_dir,
            'thumb' => [
                'source' => [
                    'url' => '{hash1}/{hash2}/{id}.jpg'
                ],
                '300' => [
                    'width' => 300,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_300.jpg'
                ],
                '800' => [
                    'width' => 800,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_800.jpg'
                ]
            ],
            'hash1' => $hash['hash1'],
            'hash2' => $hash['hash2'],
            'id' => $id
        ];

        if ($image_status['status'] == true) {
            $result = \Common\PhotoImage::imageResize($cfg, $image_status);

            if ($result) {
                if ($type == 1) {
                    $res = "http://img.jinguonet.com/act/cover/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg?v=" . time();
                } else {
                    $res = "http://img.jinguonet.com/act/content/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg?v=" . time();
                }

                return $res;
            }


        }

        return false;
    }

    public function doInput()
    {
        if (empty($_POST['ShopId'])) {
            HDshowMsg('添加失败！', ['type' => 'error', 'url' => $this->list_url]);
        }

        $data = [
            'ShopId' => intval($_POST['ShopId']),
            'CityId' => intval($_POST['CityId']),
            'Name' => trim($_POST['Name']),
            'Description' => trim($_POST['Description']),
            'StartTime' => trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'MinPrice' => $_POST['MinPrice'],
            'MaxPrice' => $_POST['MaxPrice'],
            'PriceType' => intval($_POST['PriceType']),
            'Rules' => trim($_POST['Rules']),
            'MaxOffer' => intval($_POST['MaxOffer']),
            'Sort' => intval($_POST['Sort']),
            'RewardType' => intval($_POST['RewardType']),
            'RewardDays' => intval($_POST['RewardDays']),
            'CouponId' => intval($_POST['CouponId']),
            'Amount' => intval($_POST['Amount']),
            'Status' => intval($_POST['Status']),
            'ViewCount' => 0,
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        $id = Center\Active::add($data);
        if ($id !== false && $id > 0) {
            //上传图片
            $img = $_FILES['Cover'];
            if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0 && $id) {
                // 复制图片
                $imgUrlAddre = self::saveImageUrl($id, $_FILES['Cover']);
                \Center\Active::update($id, ['Cover' => $imgUrlAddre]);
            }
            $img2 = $_FILES['ImgUrl'];
            if (isset($img['name']) && $img2['error'] == 0 && $img2['size'] > 0 && $id) {
                // 复制图片
                $imgUrlAddre2 = self::saveImageUrl($id, $_FILES['ImgUrl'], 2);
                \Center\Active::update($id, ['ImgUrl' => $imgUrlAddre2]);
            }
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }
}

$app->run();